package com.aidex.admin.controller.common;

import cn.hutool.core.util.RandomUtil;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.constant.CacheConstants;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sign.Base64;
import com.aidex.common.utils.uuid.IdUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.alibaba.fastjson2.JSONObject;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "验证码")
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired(required = false)
    private AiDexConfig aidexConfig;

    @ApiOperation(value = "图片验证码")
    @GetMapping("/captchaImage")
    public R captchaImage(String uuid, String type) throws IOException {
        JSONObject result = new JSONObject();
        boolean captchaOnOff = ConfigUtils.getConfigBooleanValueByKey("sys.captcha.onOff" , true);
        result.put("captchaOnOff" , captchaOnOff);
        if (!captchaOnOff) {
            return R.data(result);
        }
        if (StringUtils.isEmpty(uuid)) {
            return R.fail("标识不可以为空");
        }
        try {
            // 保存验证码信息
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + CacheConstants.CAPTCHA_TYPE.valueOfType(type) + ":" + uuid;

            String capStr, code = null;
            BufferedImage image = null;

            // 生成验证码
            String captchaType = aidexConfig.getCaptchaType();
            // 生成验证码
            if ("math".equals(captchaType)) {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf('@'));
                code = capText.substring(capText.lastIndexOf('@') + 1);
                image = captchaProducerMath.createImage(capStr);
            } else if ("char".equals(captchaType)) {
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
            }

            redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try {
                ImageIO.write(image, "jpg" , os);
            } catch (IOException e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
            result.put("img" , Base64.encode(os.toByteArray()));
            return R.data(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.data(R.fail(e.getMessage()));
        }
    }

    @ApiOperation(value = "短信验证码")
    @PostMapping(value = "/captchaMobile")
    public R captchaMobile(String uuid, String mobile, String type) {
        if (StringUtils.isEmpty(mobile)) {
            return R.fail("手机号不允许为空！");
        }
        if (StringUtils.isEmpty(uuid)) {
            return R.fail("标识不可以为空");
        }
        //随机数
        String captcha = RandomUtil.randomNumbers(6);
        Map<String, String> obj = new HashMap<>();
        obj.put("code", captcha);
        if(StringUtils.isEmpty(uuid)) {
            uuid = IdUtils.simpleUUID();
        }
        String verifyKey = CacheConstants.MOBILE_CODE_KEY + CacheConstants.CAPTCHA_TYPE.valueOfType(type) + ":" + uuid;
        Object object = redisCache.get(verifyKey);
        if (object != null) {
            return R.success();
        }
        // TODO 发送验证码

        redisCache.set(verifyKey, captcha, 600);
        return R.success();
    }

    @ApiOperation(value = "邮箱验证码")
    @PostMapping(value = "/captchaEmail")
    public R captchaEmail(String uuid, String email, String type) {
        if (StringUtils.isEmpty(email)) {
            return R.fail("邮箱不允许为空！");
        }
        if (StringUtils.isEmpty(uuid)) {
            return R.fail("标识不可以为空");
        }
        //随机数
        String captcha = RandomUtil.randomNumbers(6);
        Map<String, String> obj = new HashMap<>();
        obj.put("code", captcha);
        if(StringUtils.isEmpty(uuid)) {
            uuid = IdUtils.simpleUUID();
        }
        String verifyKey = CacheConstants.EMAIL_CODE_KEY + CacheConstants.CAPTCHA_TYPE.valueOfType(type) + ":" + uuid;
        Object object = redisCache.get(verifyKey);
        if (object != null) {
            return R.success();
        }
        // TODO 发送验证码

        redisCache.set(verifyKey, captcha, 600);
        return R.success();
    }
}
